Von Andreas Jordan auf Mittwoch, 02. August 2023
Kategorie: PowerShell

Execute PowerShell scripts as SYSTEM

We frequently experience situations where PowerShell scripts need to be run as local system (NT AUTHORITY\SYSTEM). For one of our customers, we wanted to use this method to store a password encrypted by Export-Clixml with the key of the local system, so that another process can decrypt and use it again with Import-Clixml.

What are the options?

Several sources on the internet describe two basic options: On the one hand the program PsExec.exe, on the other hand the Windows Task Scheduler. In the latter case, however, only the use of the graphical user interface is shown. PowerShell can also be used to create and execute a task.

Which code do we want to execute?

First, here is the PowerShell code to run as the local system:

The script takes the username in plain text, but not the password: it only receives the path to a file from which it reads the password. Why that matters is explained below in the section "Why the detour through a file?". The "finally" block then overwrites that file with null bytes and deletes it – even if the export in between fails. Optionally, the location for the file to be created can be specified. We usually use the environment variable LOCALAPPDATA for this, which is set to "C:\Windows\system32\config\systemprofile\AppData\Local" for the local system.

The script is saved as “C:\tmp\ExportCredential.ps1” in our case, this path is needed in the following code.

How do we create a task with PowerShell?

The following code does not necessarily have to be saved as a script, and can simply be customized and executed via the PowerShell ISE. The only important thing to keep in mind is to use an elevated PowerShell session.

First the business part, which asks the user for the password to be encrypted, writes it to a file with restricted access rights and assembles the arguments for PowerShell execution:

The order matters here: the file is created empty and given its access rights before the password is written into it. Anyone who writes first and sets the rights afterwards leaves the file sitting there with the folder's inherited rights for a moment.

Then the task can be created and executed:

Since the task is deleted immediately afterward, it only exists on the system for a very short time. Thus, this variant is also preferable to using the graphical interface for security reasons.

Why the detour through a file?​

Until November 2026, this section contained a code example that passed the password directly to the task as a command line argument. That has two problems, and both only show up in production.

First, the password then appears on the command line of the PowerShell process that is started. If the group policy "Include command line in process creation events" is enabled on the system – and in many companies it is – the password ends up in plain text in the security event log (event 4688) and therefore often in the central log collection as well. Microsoft explicitly points this out in the documentation for that policy. A password that is supposed to be readable only by the local system then sits for months in a place that far more people are allowed to read. With the detour through a file, event 4688 contains nothing but the path.

Second, PowerShell splits arguments at spaces. With the old version, a password containing a single space only reached the script as "-Password" up to that first space; the rest slipped onto the positional parameter "-Path". The script therefore created the file in the wrong place with the wrong password, without reporting an error. With two spaces, no file was created at all – and because the task was deleted right away, nobody ever saw it. Quotation marks alone do not solve this either, because a password that itself contains a quotation mark breaks out of them again. Through the file, every special character arrives unchanged.

The password file only exists for one to three seconds, it is restricted to SYSTEM and administrators, and the script running as the local system overwrites it before deleting it. If the task never starts, however, the file is left behind – for production use, the whole block therefore belongs in a "try"/"finally" that removes the file in any case. It also works entirely without a file, using a named pipe through which the caller hands the password to the task: more code and an additional timeout path, but the password never touches the disk.

Why the code waits for the task to finish

Start-ScheduledTask returns immediately and does not wait for the task to finish. The old version called Unregister-ScheduledTask right afterwards – that works out on a fast system, but not necessarily on a busy server. More importantly, nobody could see whether the script had succeeded at all.

The loop therefore checks two things: that the state is back to "Ready" and that "LastRunTime" is later than the start time. The second check is necessary because a task that has never run reports a "LastTaskResult" of 267011 and a "LastRunTime" from 1999. After that, "LastTaskResult" holds the return value of the script – on failure a value other than zero, which the code reports as a warning.

Bonus: How are the environment variables of the local system set?

If you want to run very little PowerShell code, for example, export only the values of all environment variables of the local system to a file, then set the value of the $actionArgument variable like this and use it to create the task:

$actionArgument = '-Command "& { gci Env: | tee C:\tmp\env_system.txt }"'

Conclusion

With a few lines of PowerShell, the Windows Task Scheduler can be controlled to create and execute a task at short notice. This allows scripts to be executed quite easily as the local system.

If your goal is to run a service account without a managed password at all, another route gets you there faster: "I don't want to know the password – Using group Managed Service Accounts for Microsoft SQL Server".

Verwandte Beiträge

Kommentare hinterlassen