Wednesday, July 22, 2015

#87: Executing Encoded Commands in Powershell

Today, we will take a look how we can avoid displaying sensitive information to users in form of text. This approach does not apply to a hacker or cracker, but it will just avoid flashing secure info to common users.

I had a requirement to connect SQL Server instance using SQL Login. If you connect to any server using Windows authentication, passwords are never revealed, but using SQL Logins in your script reveals everything as plain text. Although the login to used will have limited permission on SQL Server, but still disaplying passwords as plain text was going difficult to me. In fact, it applies to any case, we should never put passwords directly to the script as plain text.
Now, problem is clear that we will go with encryption route or we will do something else.
In Powershell, we have feature to run commands as Base-64 string. We can use this feature since Powershell v1.0.

A complete demonstration here:




Please follow below steps to achieve it :

1. Convert the command line to a Base-64 string.

$CodeLine = 'Write-Host "Hidden secret code!"'
$UniCodeLine = [System.Text.Encoding]::Unicode.GetBytes($CodeLine) 
$HexCodeLine = [Convert]::ToBase64String($UniCodeLine) 
echo "$HexCodeLine"

Description:
Line #1 : It will get the command to be executed
Line #2 : It will convert your code into Unicode string
Line #3 : It will convert Unicode string to Base-64 string
Line #5 : It will display the string. Now, you can copy paste the output to your actual code.

2. Run the command as below :

$Passwd=powershell -EncodedCommand "VwByAGkAdABlAC0ASABvAHMAdAAgACIASABpAGQAZABlAG4AIABzAGUAYwByAGUAdAAgAGMAbwBkAGUAIQAiAA=="
& sqlcmd -E -S ABC\ABC -U "User1" -P $Passwd

Description:
Line #1 : Get the output from encoded command line using -EncodedCommand parameter. Store results to $Passwd. 
Line #2 : Run the sqlcmd to SQL Server instance and pass password as $Passwd
I repeat, this does not solve the security problem completely as Base-64 string can be converted to string, but it is secure upto certain extent.

Thanks for reading.

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...