I am working on a PowerCLI script that deploy and configure VMs from a template. During the configuration phase I have to run some commands which require the Guest's root Username and Password to run Scripts on the VM. These are the Template's default credentials and they are stored as plaintext in my script. After configuration is complete I have the User change their passwords using SecureString Credentials.
What has me worried is that due to the nature of the VM's I am configuring there is a large window of opportunity for someone to access this VM if they can find the default plain-text credentials I have in my script. Is there a way of storing the default credentials in the script that is encrypted?
It's possible to store credentials encrypted against the users account using trusted storage and ConvertTo-SecureString
.
Here's how to encrypt a value against your account, where the value you want to encrypt is stored in $Password
. Make sure to set the a path to store the password in a file too, under $configDir
.
$Password = "SomeValue"
#Path to store the credential
$configDir = "$Env:AppData\WindowsPowerShell\Modules\YourScriptName\0.1\Config.ps1xml"
$password = ConvertTo-SecureString "SomeValue" -AsPlainText -Force
$password | ConvertFrom-SecureString | Export-Clixml $configDir -Force
Now, to recover the password from encryption:
$password = Import-Clixml -Path $configDir -ErrorAction STOP | ConvertTo-SecureString
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$password= [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
And you'll end up with your password stored with $password
.