Running script in non domain joined devices like linux machines or network appliance requires authentication within the script. As powershell scripts are readable, putting the password straight in the script is worst idea.
The way is to store password as a secure string in PowerShell
#Write the password to a file
$__credential = Get-Credential
$__credential | Export-Clixml D:\Script\SecPwd.dat #any file extension
#Read credentials from a file
$__credential | Import-Clixml D:\Script\SecPwd.dat
In the above script, only the user account which encrypted the password can decrypt and use the credential. If the script is moved to other system, decrypt fails.
While using the above script in scheduled tasks running with a runas account, the password decryption fails because the created and run accounts are different. So the password has to be encrypted with the runas account.
To overcome this, we can use key file to encrypt the password. AES encrypting key is used for this
$encryptionKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($encryptionKey)
$encryptionKey | out-file D:\Script\aesPasswordKey.txt
#Encrypt password with the above key
$credential = Get-Credential
$encryptionKey = Get-Content D:\Script\aesPasswordKey.txt
$credential.Password | `
ConvertFrom-SecureString -key $encryptionKey | `
Set-Content D:\Script\encrPassword.txt
This key can be used to decrypt the password when required
$user = "admin"
$password = Get-Content D:\Script\encrPassword.txt | `
ConvertTo-SecureString -Key (D:\Script\aesPasswordKey.txt)
$credential = New-Object System.Management.Automation.PsCredential($user,$password)
Note:
- Hardcoding password is always a risk.
- The key file should be placed in safe location with limited access to the runas account
- This is not 100 % full proof
Recent Comments