Secure PowerShell Scripts running via Windows Task Scheduler using MD5 Hashes to safeguard against Tampering

Over the years the number of Task Scheduled based PowerShell scripts has increased. However, this poses serious potential security risks.

The Security Issue

Given that these tasks commonly run as a service account, with additional rights, it is a potential attack vector.

Simply changing the underlying script can allow a hacker access to anything the service account has access to.Even signing the scripts can be useless as the system can be configured to ignore signing.

The Solution

I have created this one-liner that Task Scheduler can use that will only run the script if the hash of the script matches the hash listed in the one-liner. If someone tries to change this in Task Scheduler they would be required to reenter the proper password.

powershell.exe -command if ([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash([System.IO.File]::ReadAllBytes(‘C:\temp\test.ps1‘))) -eq ‘33-CD-2A-54-ED-F3-0F-94-5F-D2-97-D9-FE-4F-45-79‘) {. c:\temp\test.ps1} else {Send-MailMessage -SmtpServer smtp.server.domain.com -From whatever@domain.com -To you@domain.com -Subject ‘Failed to Run Script – Hash Not Correct’}

Notes about One Line Script Executor

  • You need to replace c:\temp\test.ps1 with the path to your script. (two places in this example)
  • You must supply the hash of the script. (use the following command to get it)

[System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash([System.IO.File]::ReadAllBytes(‘C:\temp\test.ps1‘)))

  • Script will email you if hash fails.
    • Change TO: and FROM: to match your needs.
  • Do NOT use double quotes in this script, do NOT forget that CMD will pass this to PowerShell, and will strip out double quotes.

If this helped you or perhaps you have suggestions to make it better, please do leave them in the comments.

Enjoy

-Eric