Create AES secure passwords for use in PowerShell scripting.

Something that I’ve always wanted to get away from in my scripting is leaving passwords in plain text. It fails audits and is just generally insecure and needs to be avoided at all costs. A solution I’ve come up to deal with this so far is to generate a secure key and password hash using AES. Now of course the problem with this is that you still need to secure your keys as they can be used to decrypt your hash into plain text, however the same can be said for PGP or any other reversible encryption.

#################################################################
#   Generate AES Secured Password for Scriptng                  #
#   Created by - Cameron Joyce                                  #
#   Last Modified - Dec 25 2016                                 #
#################################################################
# This script is used to generate a secured AES key and password string for use with other automation. 

# Variables
$Key = New-Object Byte[] 32   # AES Key. Sizes for byte count are 16 (128) 24 (192) 32 (256).
$UnSecPass = Read-Host "Enter Password you wish to use"
$PassName = Read-Host "Enter a filename for the password file."
$SecPass = "$UnSecPass" | ConvertTo-SecureString -AsPlainText -Force
$PasswordFile = "$env:Userprofile\Downloads\$PassName.txt" # OutFile Path for encrypted password.
$KeyFile = "$env:Userprofile\Downloads\$PassName.AES.key" # Path to Generated AES Key.

# Create Random AES Key in length specified in $Key variable.
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)

# Export Generated Key to File
$Key | out-file $KeyFile

# Combine Plaintext password with AES key to generate secure Password.
$SecPass | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile

How do we use this in real life though? Well here is an excerpt from another script I wrote to install the SCCM agent using my credentials without being logged in.

# Create secure credentials.
$User = "domain\username"
$PasswordFile = "C:\password"
$KeyFile = "C:\key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

# Using the $MyCredential in practice.
Start-Process Powershell -ArgumentList "-File C:\Temp\SCCM_Agent_Install.ps1 -Verb runAs -Credential $MyCredential"

There is much to be improved on here, however it satisfied my audit requirements and makes me considerably more comfortable that I don’t have a folder full of .ps1 files on a server with my password in plain text.

Advertisements