85

I created my own parental control app to monitor my kids activity. The app's only GUI is a task bar icon. The program is installed as admin. I'd like this program to be started up automatically as admin user on Windows startup, so that standard users cannot kill it from task manager.

I can create a registry key at:

HKLM\Software\Microsoft\Windows\CurrentVersion\Run

to make it run automatically when Windows starts up. The problem is that the program is started as the logged in (standard) user.

How can I make it run in an elevated mode? Is this possible at all in Win7?

Jonathan Komar
  • 2,678
  • 4
  • 32
  • 43
newman
  • 6,841
  • 21
  • 79
  • 126
  • 1
    A perhaps bigger problem is that the program is *not* started at all if there is no logged in user. This is a mechanism to run a program on login (like your `.login` script on Unix), not to run at boot time (like some `/etc/rc/...` script). – Kaz Dec 06 '12 at 22:08
  • @Kaz: In the context of this question, that doesn't seem to be a problem (unless trying to observe kid interaction with the login screen) – Ben Voigt Sep 11 '15 at 04:34

9 Answers9

65

You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.

This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.

I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.

From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2015-01-27T18:30:34</Date>
    <Author>Pete</Author>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <StartBoundary>2015-01-27T18:30:00</StartBoundary>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>CHUMBAWUMBA\Pete</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>"c:\windows\system32\notepad.exe"</Command>
    </Exec>
  </Actions>
</Task>

and it's registered by an administrator command prompt using:

schtasks /create /tn "start notepad on login" /xml startnotepad.xml

this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.

TeaDrivenDev
  • 6,591
  • 33
  • 50
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • 2
    "after login of a user" is not "Windows startup". – Kaz Dec 06 '12 at 22:08
  • Yes, but you don't actually have a desktop to use until you've logged in – Anya Shenanigans Dec 07 '12 at 14:05
  • 6
    @Petesh how did you get a UI-based app to run this way? When I use Task Schedule I can get an app to run but I don't see its UI. – gonzobrains Jul 13 '13 at 01:00
  • I was wondering if there is any way of doing this via registry changes. If yes, it could be scheduled even without (prior to) booting the operating system. – Sopalajo de Arrierez Jul 28 '14 at 02:25
  • Thank you for this. I manually created a Task Scheduler entry for this and it didn't work. I used your xml as a template to have OpenVPN startup on logon and it worked. I would hae sworn up and down that my manual entry was identical, but I must have made a mistake somewhere. – Paul Perrick Oct 07 '15 at 10:17
40
schtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"
EdChum
  • 376,765
  • 198
  • 813
  • 562
msPark
  • 409
  • 4
  • 2
  • 2
    Won't it run in session 0 and you will not be able to see the UI?? I wanted same thing and it did it but it was running in session 0 under my username and hence the UI was not available – Gautam Aug 21 '12 at 15:58
  • 4
    "onlogon" is not Windows startup. – Kaz Dec 06 '12 at 22:09
  • 1
    On Windows 7, it runs on the user's desktop. Try it with calc.exe. – Vladimir Panteleev Dec 13 '12 at 06:49
  • 1
    @CyberShadow I'm trying to do this with an app that requires admin rights. I see it in the task manager but its UI is not visible. – gonzobrains Jul 13 '13 at 01:01
  • I just get "Access Denied" – Joel G Mathew Jan 29 '14 at 20:59
  • 2
    Thanks for the answer. Our IT dept recently forced UAC ON via group policy for all computers on our company domain. With the sad consequence that if you run a command prompt as administrator, your drive mappings are not available. Previously, I had set up a short .bat file to run at logon via the "run" registry key which would set up all of my drive mappings. I needed a way of running a similar .bat for the SYSTEM account at startup. "schtasks /ru SYSTEM" is exactly what I needed. – Die in Sente Dec 16 '14 at 18:27
  • 1
    I created a startup schedule with this command and wondered why it didn't run on login. I launched the task scheduler GUI and look at the properties. It defaulted to only run when the laptop was charging. It doesn't look like it can be configured on command line. – MikkoP Aug 21 '15 at 16:43
  • I confirm that on Win7 the UI shows up. I tried this with ProcessExplorer (which needs to be elevated in order to be able to manipulate certain types of processes), and while the UI took maybe a minute to show up, it eventually did. Actually, ProcessExplorer can show the Session of processes, and using it to look at its own process instance, we see that it's running under Session 1. Also, its parent, `taskeng.exe` is running under Session 1. But things like `svchost.exe` are indeed reported to be running in Session 0. – Evgeni Sergeev Oct 26 '16 at 09:14
16

This is not possible.
However, you can create a service that runs under an administrative user.

The service can run automatically at startup and communicate with your existing application.
When the application needs to do something as an administrator, it can ask the service to do it for it.

Remember that multiple users can be logged on at once.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • thank you very much for prompt answer. Actually, I did try to run the app from a Window Service, but couldn't make it work. I could see the program in the task manager (as SYSTEM user), but the icon is not showing up in the taskbar. When I add Verb="runas" to StartInfo, I got an exception "Not enough storage is available to process this command". I guess that may be because there is no way to popup a GUI to ask user for confirmation. – newman Mar 25 '11 at 02:24
  • 8
    @miliu: A service cannot interact with the user. You need to make two programs that communicate with each other. – SLaks Mar 25 '11 at 02:32
6

I think that using the task scheduler to autostart programs is not very user friendly, and sometimes it has had side effects for me (e.g. tray icon for a program is not added).

To remedy this, I have made a program called Elevated Startup that first relaunches itself with administrator privileges, then it launches all files in a directory. Since Elevated Startup is now elevated, all the programs it then launches is also given administrator privileges. The directory is on the start menu next to the classic Startup directory, and works very much the same.

You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.

You can get the program here: https://stefansundin.github.io/elevatedstartup/

stefansundin
  • 2,826
  • 1
  • 20
  • 28
  • since this is the recent answer, I would like to add a comment. I am trying to do the same as the OP with my program using task scheduler on Windows 10. However, it starts my program as background process which is not what I want. I want my application to start normally as an administrator. Does your program account for this? – ThN Jun 18 '15 at 12:54
  • I believe it would. The program should start as if you right clicked the shortcut and used "Run with administrator privileges". If it doesn't behave as you want, I'd be happy to know more about your use case and make the program work for you. – stefansundin Jun 18 '15 at 22:06
3

Setting compatibility of your application to administrator (Run theprogram as an administrator).

Plug it into task scheduler, then turn off UAC.

Wawan
  • 39
  • 1
3

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}
  • That's a slick library -- Just a note, though. Running something in "realtime" isn't necessary most of the time. And you never dispose of `td` Thanks for pointing me in this direction. – Andy Feb 17 '17 at 15:02
  • 1
    @Sonic Thanks for the tip about disposal. You're right, "realtime" isn't normally necessary. This code is copied from an open source web content filter I wrote so it's necessary that it gets started up ASAP. –  Feb 23 '17 at 18:07
2

A program I wrote, farmComm, may solve this. I released it as open-source and Public Domain.

If it doesn't meet your criteria, you may be able to easily alter it to do so.

farmComm:

  • Runs at boot-up under a service, which continues when users log in or out.
    • In Session 0
    • Under the user "NT AUTHORITY\SYSTEM."
  • Spawns arbitrary processes (you choose);
    • Also in Session 0
    • "Invisibly," or without showing any user interface/GUI
    • With access to graphics hardware (e.g. GPUs).
    • Responds to the active session, even if it changes, including the Secure Desktop. This is how it:
    • Only spawns processes after a user is idle for 8.5 minutes
    • Terminates spawns when a user resumes from idle

The source scripts are available here:

https://github.com/r-alex-hall/farmComm

Alex Hall
  • 956
  • 10
  • 18
2

You should also consider the security implications of running a process as an administrator level user or as Service. If any input is not being validated properly, such as if it is listening on a network interface. If the parser for this input doesn't validate properly, it can be abused, and possibly lead to an exploit that could run code as the elevated user. in abatishchev's example it shouldn't be much of a problem, but if it were to be deployed in an enterprise environment, do a security assessment prior to wide scale deployment.

Curtis
  • 41
  • 3
  • Some programs require elevation and are not necessarily subject to security problems. For example, a program that monitors system temperature and displays it in the notification area would need elevation to access the hardware, and it would need to be auto-run, yet security is moot a point for it. – Synetech Feb 10 '16 at 18:20
  • I disagree that running software like this is doesn't matter. I've used software just I agree with you that some software requires elevated privileges to run, but I disagree with you that running certain types of software at elevated levels doesn't matter. I have used software exactly like you are describing to gain a foothold in a system as a root/admin or elevated user. From there you have access to any other software or service on that system at that privilege level. If not on that system, you can use that privilege level to pivot to another system on the network. – Curtis Jul 06 '21 at 12:24
  • Yes, obviously that can be abused, but that requires intentional abuse (like you said you did). I'm talking about trusted users and a trusted program. Regardless of how you feel about it, some programs _require_ elevation. Ever since UAC, such programs that need to be auto-run have been a massive pain, and even ones that use a service or a scheduled task rarely work correctly and require all kinds of work-arounds to (try to) get working which just ends up as an EVEN BIGGER security issue. – Synetech Jul 07 '21 at 13:52
-3

I think the task scheduler would be overkill (imho). There is a startup folder for win7.

C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.

Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.

Good luck!

zhengtonic
  • 720
  • 12
  • 25
  • 6
    This will not work. Windows will ignore Startup shortcuts set to run as Administrator. – Vladimir Panteleev Jan 05 '14 at 09:41
  • Really? Have you tried? Because its working fine on my side. I have to auto-start my LogitechSoundManager as Administrator in order for the surround sound to work ... – zhengtonic Mar 04 '14 at 09:39
  • I have this problem too, even though the shortcuts in the startup folder have the option checked "run as administrator", they still won't load on startup. Anyone know any ways to fix this? – ycomp Dec 01 '14 at 09:12
  • 2
    CyberShadow was right the UAC of the computer was off. StartUp shortcuts as admin does not work ... one has to use the taskscheduler – zhengtonic Dec 01 '14 at 12:11
  • I found at least on Windows 10 this doesn't work. As @vladimir-panteleev said, Windows simply seems to ignores it. – E. van Putten Jul 13 '18 at 11:01