1
votes

I want to keep my powershell scripts on my local server in base64 but when run from schtasks or locally using powershell -file /path/to/ps1 they self decode. Is this possible??

I tried:

function Decode { $data = 'base 64 script'

[System.Text.Encoding] ::ASCII.GetString([System.Convert]::FromBase64String($data))}

Decode

This does not work. Any ideas?

1
Out of curiosity, what is the driver for this? I used once the -EncodedCommand as suggested but this was because I was generating my code. - Alex Sarafian

1 Answers

3
votes

I see at least two options for this situation. One option is to send the base64 encoded command to Powershell.exe using the -EncodedCommand parameter. The second option is to create your decoding script to accept another script that contains the base64 encoded command as a parameter value.


Option 1: Passing the Encoded Command

This assumes your base64 encoded command is a string version of your PowerShell commands formatted using UTF-16LE character encoding (Unicode). Let's also assume that you have a script called Encoded.ps1 that contains your base64 encoded command. With the prerequisites met, you can do the following:

Powershell.exe -EncodedCommand (Get-Content Encoded.ps1)

Option 2: Running a Decode Script Against the Encoded Script

The unicode requirement does not matter in this case (you can use ANSI if you like). You just need to know your original command string encoding so you can properly decode it. We will assume ASCII character set. Let's also assume that Encoded.ps1 contains your base64 encoded command.

First, let's create the decode script called Decode.ps1.

# Decode.ps1
param([string]$FilePath)

$64EncodedData = Get-Content $FilePath  
$DecodedData = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($64EncodedData))

& ([scriptblock]::Create($DecodedData))

Second, let's run the Powershell.exe command to decode Encoded.ps1 and execute the decoded command.

Powershell.exe -File Decoded.ps1 -FilePath Encoded.ps1

The code above is not intended to display the contents of the decoded commands but rather execute the decoded commands. $FilePath is the path to your Encoded.ps1 file, which contains a base64 encoded string from an ASCII encoded character set. You can change to whichever encoding applies to your situation in the Decode.ps1 file. $DecodedData contains the original command strings. Finally, a script block is created containing $DecodedData and then called with the call operator &.