Monday, November 7, 2016

Ways to secure your password within your PowerShell scripts

This is a guest post  Mr. Troy Collins

Resonantly I had a problem given to me by a colleague at work.


Overview of the problem:
The Citrix team has some Powershell scripts running to gather Citrix information 2 times a day via schedule task within Windows. A security issue occurred with the SMTP relay server that he was using for sending out the reports and the team that managed it forced all users to authenticate via user/pass and a mailbox to send messages.  

The problem:
The script has to run as one account that has access to the Citrix environment and the account they gave to send out the messages was different.  So who do we run the scheduled task as? The Citrix account to gather the data or send with another account and secure the password?

Solution:
I created 2 scripts one to create the secure password that you use only once and the other was updated version of the original.

Create the password hash:

#here we ask for the users input.  -AsSecureString hides the password on the screen

$pass = Read-Host "Enter Password" -AsSecureString
#Next we convert the pass and export the hash string to text file.  ( I found it easyer to copy/paste from the text file insted of the screen) 
"$pass" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | out-file ./passwd.txt
#opens the text file for you to copy the hash
invoke-item ./passwd.txt
# this part is just to delete the file to leave nothing behind.
 Write-host "would you like to delete the password file?" -ForegroundColor Yellow 
    $Readhost = Read-Host " ( y / n ) " 
    Switch ($ReadHost) 
     { 
       Y {
remove-item ./passwd.txt -force -confirm:$false

       N {Write-Host "Your Done..."} 
}

Now we take the hash we created and added it to whatever script we need to have authentication with. 

This example we are using the username / password to authenticate to e-mail server to send a message but you could use this for any command or script that can use the -Credential string.  

$username = "domain\username"
$pass = "01000000d08c9ddf0---HASH----00c04fc297eb0100000000425808144"
$passwd = ConvertTo-SecureString -String $pass
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $passwd

send-MailMessage -smtpServer smtp.someserver.com

 -Credential $cred -from 'user@somedomain.com' -to 'someone@domain.com -subject
 'Test' -attachment test.txt -body $message​

After thought:
Although this is more secure than just putting the password in the script it's not impossible to get the password, so NTFS permissions from the O/S should also be used to this script file itself. 

Enjoy

No comments:

Post a Comment