Petya: disabling remote execution of psexec

This morning in response to reports of an outbreak of yet more malware I wrote a quick blog post on one way to stop the SysInternals psexec from being allowed to execute by using the Image File Execution Options registry key mechanism – see here for that post.

My technique was, and still is sound, but @RennJohnny correctly pointed out that if the psxec.exe executable was renamed then my approach would not work. I therefore set about finding another way to stop psexec from running for those who don’t (yet) have security software in place to stop the exploit. Note that you need to be running it on a system where you are an administrator and have the same rights on the remote system to be attacked. As the disposable virtual machine that I used for my testing is not on a domain, I passed explicit credentials to psexec for my testing – I don’t believe Petya operates this way but my solution will still work.

So when psexec is used to run something on a remote system, it works by creating a new service executable called psexesvc.exe which is embedded within the original psexec.exe file. This is copied to the Windows folder on the remote machine via the admin$ default share (hence why you need to be an admin to get psexec to work remotely). It then creates the PSEXESVC service with this, now local, executable, starts it and then runs the specified command.

What I found was that even when I copied psexec.exe to another file name, the file produced and copied to the remote system was still called psexesvc.exe. This is what happens when you run the copied psexec.exe and tell it to invoke a command on a remote machine:

psexesvc allowed

 

On that remote system we can then see this has been created in the services registry key:

psexesvc registry

How do we stop it? I reckon that the easiest way is to use good old Image File Execution Options (IFEO) mechanism again but this time we create the key “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\PSEXESVC.exe” and in there create the REG_SZ value called “Debugger” and set it to “svchost.exe”. Now when we try and run psexec to execute on the system where we just patched the registry, this happens instead:

psexesvc blocked

What happened? Well when the Service Control Manager (SCM) on the remote machine was asked to start the PSEXESVC service, it started the psexesvc.exe process but the IFEO entry we created caused it to run svchost.exe instead but as that can’t be used as a standalone service, it failed to start so SCM reported this to psexec which is the error we see above. You will also get this in the System event log of the remote system:

psexesvc eventlog.PNG

One way to roll it out to all your computers is to put the above registry value into a Group Policy Preference that applies to those computers.

You can also create a dummy psexesvc.exe file in your Windows folder, remove all permissions and change the owner to, say, TrustedInstaller, and that will also prevent it from running.

I hope this helps some of you and stay safe (and don’t run routinely with admin privileges!).

Advertisements

Petya: easily disabling access to psexec

So it seems there is yet another piece of ransomware in the wild which is more sophisticated than Wannacry as it uses multiple attack vectors. I have read that one of these is once a machine is infected that it uses the great SysInternals utility psexec.exe, and possibly Microsoft’s command line WMI utility wmic.exe, to spread further. Whilst there are products, like Ivanti Application Control, formerly AppSense Application Manager, that can be used to blacklist these, if you haven’t got those products today then you need a way of stopping these attack vectors. One way would obviously be to delete wmic.exe, or remove NTFS permissions to it, but you can’t do that for psexec since presumably the malware is either downloading it or has it embedded within its payload.

Here is where we can use the little known Image File Execution Options (IFEO) registry key to put a temporary, or permanent, block on these, or any other executables, so they cannot run. We can either get them to fail silently or run a script informing the users that their machine is infected.

IFEO has been around for 20+ years – in fact the very first version of the software that I wrote that became AppSense Application Manager used this feature. It is great for debugging but is also an attack vector itself for malware as it can be used to disable security programs with the same technique. One mitigating factor is that because the key is in HKLM, you need administrative rights to write to it and we don’t let any user run with administrative rights when they are running web browsers, email, Office products, etc. now do we?

So what do I do? In its simplest form, create the key “psexec.exe” in “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options” and then create a REG_SZ value called “Debugger” and set it to “svchost.exe” as below:

ifeo psexec

Job done! If you run psexec.exe before adding the above settings you’ll see something like this:

psexec before

But once the registry key and value are in place we get this instead:

psexec after

Attack vector thwarted! But aren’t we then running a service because svchost.exe is being run instead? No, service executables can’t just be run from the command line, they need to be invoked via the Service Control Manager (SCM), so this invocation of svchost.exe just fails silently.

Do the same with a wmic.exe key and that’s both supposed attack vectors blocked for now.

You can also set the value to run a script although you need to ensure that the script itself cannot be compromised using file system security. For instance, if I set the Debugger value to this:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file c:\temp\infected.ps1

Note the use of the full path so we don’t accidentally run a malicious powershell.exe (unless your whole system is compromise!) and if using PowerShell rather than cmd.exe ensure that your PowerShell execution policy allows the script to run.

My c:\temp\infected.ps1 script contains just  this:

$null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

$null = [Microsoft.VisualBasic.Interaction]::MsgBox( "Your system is infected - call IT now!" , 'OkOnly,SystemModal,Critical' , $MyInvocation.MyCommand.Name )

then when psexec is run a user will get this popup:

infected

How do I roll this out quickly in an enterprise? Unless you’ve already got something that can push out registry settings to multiple computers then I would suggest that Group Policy Preferences is one of the easiest ways of achieving this.

When your security software is up to date then you might want to delete the key/value unless you need to run psexec.exe for other reasons (it is a great tool and I hope it isn’t blocked by anti-virus software in the future).

It may also be worth changing the permissions on the sethc.exe (and wmic.exe) keys you create such that they are read-only to everyone, admins included, just in case further malware tries to target these keys. In fact, why not protect the whole IFEO key, particularly if you are letting people logon with administrative rights?

I  hope this helps and stay safe people!

A Technique to Run Scripts Asynchronously via AppSense Environment Manager

Whilst AppSense Environment Manager (EM) has a rich set of trigger points, such as logon and reconnect, where you can run built-in actions or scripts, until very recently there was no built-in way of running something say five minutes after logon or every thirty minutes.

I’ve seen techniques that create scheduled tasks, which you can do directly in a PowerShell script rather than having to modify XML task templates, but with these you still have to get the script you want to run onto the local file system. Whilst I came up with a method of embedding any arbitrary file into an AppSense EM configuration, such as image files (see here), that approach is a little cumbersome, particularly if you need to change the embedded script.

I find an easier way to achieve this goal is to write a script inside an EM logon action that takes a copy of itself to a local file and then invokes powershell.exe to run it so that it runs outside of EM thus allowing the logon to finish but the newly launched script is still running as it is hosted inside an asynchronous powershell.exe process. Inside this script you can then wait for any period of time and then perform an action and either exit or loop around ad infinitum, or at least until logoff.

It works by looking to see if the -async option has been specified when the script was run. When EM runs the script, it won’t specify any options so we detect this and make it fire off a copy of the same script, since EM will delete the original when the script it invoked finishes, via powershell.exe which will take a different path through the code because the -async parameter is specified this time.

There’s an example version 10 EM configuration available for download here although the technique will work with any EM version. You will need to put your code into the PowerShell custom action, after the comment line reading “we are now outside of EM so can trigger later”, to perform whatever you need it to do. You might just want it to do something every few minutes or hours or you could put a file system or registry watcher in to trigger when something specifically changes (now there’s an idea for a future post if ever there was one!).

If you need the script to run elevated then simply set the action to run as System in the configuration but remember that environment variables and HKCU will not be for the logged on user but for the System account.

If you are also using AppSense Application Manager to prohibit powershell.exe then as long as you have configured it to ignore restrictions during logon then  it should be ok but you could always add a Process rule for EMUser.exe to allow powershell.exe child processes.

Updated Hyper-V Clone from Disk Script

Back in 2015 I wrote a PowerShell script, which has a GUI, to create new Hyper-V VMs from existing VHD and VHDX files. The original blog post, “Poor man’s Hyper-V cloning from VHD/VHDX”, is available here.

Now that I’ve finally got a Windows 10 laptop with Hyper-V capability, I’ve made a few additions to the script since I’m using Hyper-V, and thus the script, pretty much daily now. For example, I have SysPrep’d Windows 10 and Server 2016 disks so I can quickly create new fresh VMs simply by right or double clicking on the relevant VHDX file in explorer. If you select the linked clone option, so the whole source disk does not have to be copied, the creation, and optional automatic starting, takes only a few seconds.

These enhancements include:

  1. Install (and uninstall) option to integrate into explorer’s right click menu without having to go near the registry yourself (apparently it scares some people!).
  2. Addition of a notes field which will go into the notes for the VM, if specified.
  3. Option to hide the parent PowerShell script window so it looks cleaner although may make any errors more difficult to track down.

I hope you find it as useful as I do.

The updated script is available here.

Fixing missing Outlook reminders

Ever found that you’ve missed a meeting because Outlook didn’t remind you? It has certainly happened to me and seems linked to copying and pasting appointments via dragon drop or if someone sends you a meeting request which doesn’t have a reminder set in it. So rather than risking missing something which might be vaguely important and incurring a colleague’s or customer’s wrath, I’ve written a VBA macro that will find and fix calendar items that do not have a reminder.

If it finds any non-all day appointments without reminders, it will prompt you once for the reminder time to set, in minutes with a default of 10, and then apply that too all appointments it found.

reminder prompt

One it has finished it will inform you what appointments it changed:

reminder fixer

You can run it manually from the VBA window or I like to add macros to the ribbon which you can do by right clicking on the ribbon and selecting “Customize the Ribbon”.

reminder macro in ribbon

The code can be downloaded here. I hope it will help you never unintentionally miss a meeting again!

Please note that I haven’t tested it when running in a US locale, as the macro constructs a date string to restrict appointments to those in the future, but I hope that the mechanism I’ve used will work. It will write debug to the Immediate window (view by pressing Ctrl G) in the VBA console.

Regrecent comes to PowerShell

About 20 years ago, after I found out that registry keys had last modified timestamps, I wrote a tool in C++ called regrecent which showed keys that had been modified in a given time window. If you can still find it, this tool does work today although being 32 bit will only show changes in Wow6432Node on 64 bit systems.

Whilst you might like to use Process Monitor, and before that regmon, or similar, to look for registry changes, that approach needs you to know that you need to monitor the registry so what do you do if you need to look back at what changed in the registry yesterday, when you weren’t running these great tools, because your system or an application has started to misbehave since then? Hence the need for a tool that can show you the timestamps, although you can actually do this from regedit by exporting a key as a .txt file which will include the modification time for each key in the output.

The PowerShell script I wrote to replace the venerable regrecent.exe, available here, can be used in a number of different ways:

The simplest form is to show keys changed in the last n seconds/minutes/hours/days/weeks/years by specifying the number followed by the first letter of the unit. For example, the following shows all keys modified in the last two hours:

.\Regrecent.ps1' -key HKLM:\System\CurrentControlSet -last 2h

We can specify the time range with a start date/time and an optional end date/time where the current time is used if no end is specified.

.\Regrecent.ps1' -key HKLM:\Software -start "25/01/17 04:05:00"

If just a date is specified then midnight is assumed and if no date is given then the current date is used.

We can also exclude (and include) a list of keys based on matching a regular expression to filter out (or in) keys that we are not interested in:

.\regrecent.ps1 -key HKLM:\System\CurrentControlSet -last 36h -exclude '\\Enum','\\Linkage'

Notice that we have to escape the backslashes in the key names above because they have special meaning in regular expressions. You don’t need to specify backslashes but then the search strings would match text anywhere in the key name rather than at the start (which may of course be what you actually want).

To specify a negation on the time range, so show keys not changed in the given time window, use the -notin argument.

If you want to capture the output to a csv file for further manipulation, use the following options:

.\regrecent.ps1 -key HKCU:\Software-last 1d -delimiter ',' -escape | Out-File registry.changes.csv -Encoding ASCIII

I hope you find this as useful as I do for troubleshooting.

Send To Mail recipient replacement

It has bugged me for years that Outlook, up to and including 2016, blocks the main Outlook window if you right-click on files in explorer and choose “Mail recipient” from the Send To menu. So if you leave this draft email open, you won’t get any new emails (which isn’t necessarily a bad thing, for a while!). I therefore decided to fix it, or rather provide an alternative, by writing a PowerShell script.

The script is available here and it can be used to install itself into the running user’s SendTo menu by creating a shortcut that invokes powershell.exe on the script:

& '.\Send Outlook Email.ps1' -install "Mail recipient"

This will replace the existing “Mail recipient” shortcut, as long as you also specify the -overwrite option, but you can leave it in place and create a new shortcut for this script simply by giving a different name to the -install argument.

Should you want to, the original shortcut can be restored thus:

& '.\Send Outlook Email.ps1' -install "Mail recipient" -restore

or if you’ve created an additional shortcut, rather than replacing the default one, use -delete instead of -restore.

The additional features it provides are:

  1. It will make copies to “.txt” files of scripts, which would normally be blocked, such as .vbs or .cmd (the list of file types can be changed in the script)
  2. It will put binary files such as .exe files, which would normally be blocked, into a zip file and attach the zip file instead (these may still be blocked though)
  3. It will warn you if your total size of all attachments exceeds 20MB (this limit can be changed in the script) which may cause the send to fail depending on your mail server’s limits

The script can take various other parameters such as -subject, -body and -recipients but these can only be used when calling the script manually from a PowerShell session or another script since using it from explorer just calls the script with a list of file names to attach. However, you can change the default values of these variables in the script so that they will work when you use the send to menu item within explorer. There are comments in the script explaining how to achieve this.

By default, it uses the same subject and body text as the built-in “Email recipient” shortcut but if you don’t like this text, find the declaration of the “$noBody” variable in the script and change it from “$false” to “$true”. Here’s a screenshot of the email generated with that tweak made and with three files selected, an .exe, .txt and .ps1, when the Send To option was invoked:

outlook-send-to-email

Note that the .ps1 file has been morphed into a .txt file and the .exe has been placed into a zip file.

Oh, and my Outlook main window is fully operational whilst you add whatever body text, etc you want to this email before sending it.