<October 24, 2024>
SecureString a golden tip to improve the security of your PowerShell scripts!

Discover how to elevate the security of your PowerShell scripts with the help of SecureString. Learn how to securely store and use sensitive authentication data, such as passwords and API tokens, in your scripts. With SecureString, you can encrypt this data so that it is not readable by unauthorized users. Also, find out how to periodically change the password of the account used and ensure that no traces of sensitive information are left behind. Enhance the security of your scripts and minimize the risk of data breaches with SecureString.

securestring

Regularly, you encounter authentication details of an API or an account with high privileges that are directly used in a PowerShell script. This can happen without malicious intent, often just to quickly make a correction. However, unnoticed, the script remains, and the password or tokens are never changed, posing a security risk.

Fortunately, there are better ways to handle this situation. After some research with a former colleague (Ilyaaz Noerkhan), we came across a solution called "Secure String". This is a method to replace readable data with encrypted information, making them more securely stored and used. Moreover, if you perform this process under a specific user account, only that account can make the data usable again. All you need for this is PowerShell version 7.0 or higher.

Creating a SecureString

The procedure is actually quite simple. You start PowerShell under the account you want to use to periodically run the script. Then you use the following syntax to process the username:

“Username” | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File “Secure_Username”

In the same way, you can process the password, or for example, an API token:

“Password” | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File “Secure_Password”

This creates two files where the username and password are stored encrypted. In your script, you can then add the following lines:

$Username = Get-Content “Secure_Username” | ConvertTo-SecureString $Username = ConvertFrom-SecureString -SecureString $Username -AsPlainText

$Password = Get-Content “Secure_Password” | ConvertTo-SecureString $Password = ConvertFrom-SecureString -SecureString $Password -AsPlainText

In this way, you first read the encrypted files and temporarily convert the “Secure Strings” into usable variables. These variables are only available during the execution of the script and are not readable if the script is found or stored somewhere as a backup. This increases the security of the sensitive data.

The fact that you do not know the actual username makes it even harder for potential malicious actors to gain access to the data. Guessing the correct combination of username and password becomes virtually impossible.