Running powershell scripts with encrypted passwords.
We sometimes see datasource scripts with passwords in the body of their script. For testing this is fine, but in production datasource scripts, passwords in plain view isn’t just bad, it should be a cardinal sin.
You can use Powershell to secure a password by creating a PSCredential object that uses the cmdlet Get-Credential and stores the output into a file. Note that it saves as a System.Security.SecureString.
Now you can use the file in your script:
$hostname= "##HOSTNAME##"
$pass= Get-Content "\\Encryptedfile.txt"
$user= "##PS.USER##"
$password1= ConvertTo-SecureString -String $pass
When your script is finished just run it in powershell GUI to check it works fine. Make sure you alter our tokens to the correct values.
We had a recent case that when the collector tries to run the datasource script it failed. The below error was in the logs.
New-PSSession : [PROD-TP-DB01] Connecting to remote server HOST failed with the following error message :
WinRM cannot process the request. The following error with errorcode 0x8009030e occurred while using Negotiate authentication: A specified logon session does not exist. It may already have been terminated.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
The script is failing with an authentication error. Even though it works fine in the Powershell GUI. The reason for this was the account the collector ran under.
PowerShell uses the Windows Data Protection API (DPAPI) to encrypt/decrypt your strings. That means if you created the file using one user account only the same user account on the same computer will be able to use this encrypted string. So the collector account cannot read the file Encryptedfile.txt. We proved this by running the Powershell GUI under the same account your collector uses. So make sure that you create the file using the same account.
Keep in mind that if you change the collector account, the script will fail. It is possible that you can encrypt the file using a machine key, which means any user on the collector can use the file and decrypt it, but that’s for another post!